﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JackProjectTemplate.Shared.Utilities
{
    public class CouponCodeUtil
    {
        private static readonly char[] _codePool = ['3', 'X', 'n', '1', 'x', 'z', '6', 'I', 'O', 'u', '4', 'o', 'w', 'i', 'E', '7', 'q', '9', 'l', 'h', 'D', 'k', 'K', '5', 'L', 'Z', 'r', 'W', 'B', 'U', 'N', 'e', 'G', 'H', 'C', 'A', 'T', 's', 'a', 'g', 't', 'f', 'R', 'v', '8', 'j', '0', 'd', '2', 'c', 'J', 'F', 'S', 'Q', 'P', 'p', 'M', 'V', 'm', 'Y', 'y', 'b'];
        private static readonly int _poolSize = _codePool.Length;
        private static readonly int[] _weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        private static readonly int _weightSize = _weights.Length;

        public static string GenerateCode()
        {
            long uniqueId = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0);

            StringBuilder codeBuilder = new();
            int sum = 0;
            int position = -1;

            char currentChar;
            int weight;
            while (uniqueId >= _poolSize)
            {
                long poolPosition = uniqueId % _poolSize;
                uniqueId /= _poolSize;
                currentChar = _codePool[poolPosition];
                codeBuilder.Append(currentChar);

                position++;
                weight = _weights[position % _weightSize];
                sum += weight * currentChar;
            }

            currentChar = _codePool[uniqueId];
            codeBuilder.Append(currentChar);

            position++;
            weight = _weights[position % _weightSize];
            sum += weight * currentChar;

            position = sum % _poolSize;
            codeBuilder.Append(_codePool[position]);

            return codeBuilder.ToString();
        }

        public static bool Verify(string code)
        {
            if (string.IsNullOrWhiteSpace(code) || code.Length < 2) return false;

            char[] parts = code.ToCharArray();
            int sum = 0;
            int weight;
            char part;

            for (int i = 0; i < parts.Length - 1; i++)
            {
                part = parts[i];
                weight = _weights[i % _weightSize];
                sum += weight * part;
            }

            int position = sum % _poolSize;
            return parts[^1] == _codePool[position];
        }
    }
}
